package com.szosen.jkzj.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.szosen.database.DBService;
import com.szosen.database.HealthRecord;
import com.szosen.database.base_info;
import com.szosen.database.xueya;
import com.szosen.idcardActivity.IDCardActivity;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.ggws.GGWSActivity;
import com.szosen.jkzj.activity.mbgy.MBGY_Main;
import com.szosen.json.database.ArchiveBean;
import com.szosen.json.database.JSONDBService;
import com.szosen.util.ContantsTools;
import com.szosen.util.FourCloumAdpter;
import com.szosen.util.MultiPrintTool;
import com.szosen.util.ToastTool;
import com.szosen.util.Tools;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/***
 * 用户列表，进入该界面显示当前医生负责的所有用户，医生可以创建用户;
 */
public class UserListActivity extends BaseActivity {

    private Context context;
    private JSONDBService dbService;
    private static FourCloumAdpter mAdapter;
    private List<String[]> mListDatas;
    Spinner sp_role;
    private TextView tv_selectedShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userlist);
        context = this;
        initView();
        Log.i(getLocalClassName(), "执行UserListActivity的onCreate犯法");
    }

    @Override
    @SuppressLint("ResourceAsColor")
    protected void onResume() {
        super.onResume();
        // 如果从result来的。就不刷新列表了
        if (isFromResult) {

        } else {
            loadData();
//            mAdapter.putAllDataSelected(false);
        }
        isFromResult = false;
    }


    /***
     * 跳转到离线记录的列表
     *
     * @param view
     */
    public void goToOfflineList(View view) {
        Intent intent = new Intent(UserListActivity.this,
                OfflineUploadListActivity.class);
        intent.putExtra(BaseActivity.ACTIVITY_FLAG, flag);
        startActivity(intent);
//        mAdapter.putAllDataSelected(isAllSelect);
//        isAllSelect = !isAllSelect;
    }

    /***
     * 跳转到设置药物列表
     */
    public void yaowulists(View view) {
        Intent intent = new Intent(UserListActivity.this,
                YaowudatasMainActivity.class);
        startActivity(intent);
    }

    public void initView() {
        flag = getIntent().getStringExtra(BaseActivity.ACTIVITY_FLAG);
        switch (flag) {
            case BaseActivity.ACTIVITY_FLAG_JKDA:
                Button userlist_uploadall = (Button) findViewById(R.id.userlist_uploadoffline);
                //userlist_uploadall.setVisibility(View.GONE);
                add_new_user_button = (Button) findViewById(R.id.add_new_user_button);
                add_new_user_button.setVisibility(View.VISIBLE);
                super.setTitleContent("【健康档案】");
                break;
            case BaseActivity.ACTIVITY_FLAG_JKTJ:
                super.setTitleContent("【健康体检】");
                break;
            case BaseActivity.ACTIVITY_FLAG_MBGY:
                super.setTitleContent("【慢病干预】");
                Button userlist_yaowulists = (Button) findViewById(R.id.userlist_yaowulists);
                userlist_yaowulists.setVisibility(View.GONE);
                break;
            case BaseActivity.ACTIVITY_FLAG_GGWS:
                super.setTitleContent("【公共卫生】");
                break;
            default:
                break;
        }
        ListView listView = (ListView) findViewById(R.id.user_listview);
        mListDatas = initTitle();
        mAdapter = new FourCloumAdpter(context, mListDatas, mHandler);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(itemClickListener);
        listView.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(final AdapterView<?> parent,
                                           View view, final int position, long id) {

                AlertDialog.Builder builder = new AlertDialog.Builder(
                        UserListActivity.this);
                builder.setMessage("您确定要删除该健康档案？");
                builder.setPositiveButton("确定",
                        new AlertDialog.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                String[] ss = (String[]) parent
                                        .getItemAtPosition(position);
                                // 用时间为唯一标准查询或者插入
                                String time = ss[4];
                                ArchiveBean ab = new ArchiveBean(time);
                                JSONDBService.delete(ab);
                                // 通过时间的主键来删除健康档案
                                HealthRecord hr = new HealthRecord();
                                hr.setTime(time);
                                DBService.delete(hr);
                                loadData();
                            }
                        });
                builder.setNegativeButton("取消", null);
                builder.create().show();
                return true;
            }
        });
        List<String> sp_datas = new ArrayList<>();
        String[] multiprint_items = getResources().getStringArray(R.array.multiprint_items);
        for (String item : multiprint_items
                ) {
            sp_datas.add(item);
        }
        ArrayAdapter mSp_adapter = new ArrayAdapter<String>(this,
                R.layout.userlist_spinner_item, sp_datas);
        mSp_adapter.setDropDownViewResource(R.layout.userlist_spinner_item);
        sp_role = (Spinner) findViewById(R.id.userlist_sp_printitems);
        sp_role.setAdapter(mSp_adapter);
        sp_role.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                selectedPrintItem = (String) parent.getSelectedItem();
                Log.i(getLocalClassName(), "你选择的打印item" + selectedPrintItem);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        tv_selectedShow = (TextView) findViewById(R.id.userlist_tv_selected_show);
        CheckBox userlist_heal_cb_selectAll = (CheckBox) findViewById(R.id.userlist_heal_cb_selectAll);
        userlist_heal_cb_selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mAdapter.putAllDataSelected(isChecked);
                int size = mAdapter.getMapData().size();
                tv_selectedShow.setText(size + "人");
            }
        });
    }

    /**
     * 默认选择的打印的item为健康档案
     */
    String selectedPrintItem = ContantsTools.MultiPrint.PRINTITEM_JKDA;

    public void createJktjfrommeasureData(View view) {
        // 先循环所有人，然后获取某人的每个测量情况。
        HealthRecord healthRecordBean = new HealthRecord();
        // healthRecordBean.setIdCard(idCard);
        xueya xy = new xueya();
        List<Object> xys = DBService.getAll(xy);
        for (int i = 0; i < xys.size(); i++) {

        }
    }

    public String getjktjTimeFromMeasureTime(String idCard, String measureTime) {
        // 根据测量的数据内容来一键生成体检表。
        if (measureTime.contains("/")) {
            measureTime = measureTime.replace("/", "-");
        }
        // 获取某一个人的体检表。
        // 通过身份证查询这个人有多少个体检表。判断数据
        base_info base = new base_info();
        base.setIdCard(idCard);
        List<base_info> lists = (List<base_info>) DBService.queryByIdCard(base);
        System.out.println("lists体检表偶的长度" + lists.size());
        for (int j = 0; j < lists.size(); j++) {
            base_info bi = lists.get(j);
            String checkDate = bi.getCheckDate();
            if (measureTime.equals(checkDate)) {
                return bi.getTime();
            }
        }
        return "";
    }

    //items的数据0为姓名 1 为年龄 2为身份证号 3为性别 4 time 5 序号
    private OnItemClickListener itemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            String[] data = mListDatas.get(position);
            BaseActivity.setIdCard(data[2]);
            ArchiveBean queryBean = new ArchiveBean();
            queryBean.setIdcard(data[2]);
            List<Object> list = (List<Object>) dbService.queryByIdCard(queryBean);
            if (list != null && list.size() > 0) {
                ArchiveBean ab = (ArchiveBean) list.get(0);
                BaseActivity.setArchiveBean(ab);
            }
            BaseActivity.setName(data[0]);
            HealthRecord hr = new HealthRecord();
            hr.setIdCard(data[2]);
            hr.setPersonName(data[0]);
            Intent intent = new Intent();
            switch (flag) {
                case BaseActivity.ACTIVITY_FLAG_JKDA:
                    intent.setClass(context, UserDetail.class);
                    BaseActivity.setJKDATime(data[4]);
                    break;
                case BaseActivity.ACTIVITY_FLAG_JKTJ:
                    intent.setClass(context, HealthCheckList.class);
                    break;
                case BaseActivity.ACTIVITY_FLAG_MBGY:
                    intent.setClass(context, MBGY_Main.class);
                    break;
                case BaseActivity.ACTIVITY_FLAG_GGWS:
                    intent.setClass(context, GGWSActivity.class);
                    break;
                default:
                    break;
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    };

    private List<ArchiveBean> hrs;
    private String flag;
    private Button add_new_user_button;

    /***
     * 初始化数据，提供表头
     *
     * @return
     */
    private List<String[]> initTitle() {
        List<String[]> datas = new ArrayList<String[]>();
        // datas.add(title);
        return datas;
    }

    public void uploadAll(View view) {

    }

    boolean isFromResult = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String idCard = null;
        if (requestCode == 0 && resultCode == 0) {
            if (data == null) {
                return;
            }
            idCard = data.getStringExtra("IdCard");
            System.out.println("返回的idCard是" + idCard);
            if (TextUtils.isEmpty(idCard)) {
                return;
            }
            isFromResult = true;
            // 因为是全部更新，所以更新前先清空集合
            mListDatas.clear();
            dbService = JSONDBService.getInstance(context);
            ArchiveBean archiveBean = new ArchiveBean();
            archiveBean.setIdcard(idCard);
            // 通过idcard来查询用户。
            List<Object> list = (List<Object>) dbService.queryByIdCard(archiveBean);
            hrs = new ArrayList<ArchiveBean>();
            for (int i = 0; i < list.size(); i++) {
                ArchiveBean ab = (ArchiveBean) list.get(i);
                // String[] 的gettime为主键。
                mListDatas.add(new String[]{ab.getName(), Tools.getYearoldByIdcard(ab.getIdcard()) + "", ab.getIdcard(),
                        ab.getSex(), ab.getTime(), (i + 1) + ""});
                mAdapter.notifyDataSetChanged();
                hrs.add(ab);
            }
        }
    }

    public void searchUser(View view) {
        loadData();
        EditText et_search = (EditText) findViewById(R.id.query_et);
        String idCard = et_search.getText().toString().trim();
        if (TextUtils.isEmpty(idCard)) {
            ToastTool.showShort(context, "请输入搜索内容！");
            return;
        }
        if (mListDatas != null && mListDatas.size() > 0) {
            List<String[]> tempList = new ArrayList<String[]>();
            // tempList.addAll(mListDatas);
            for (int i = 0; i < mListDatas.size(); i++) {
                String[] item = mListDatas.get(i);
                if (item[0].contains(idCard) || item[1].contains(idCard)) {
                    tempList.add(item);
                } else {
                    // mListDatas.remove(item);
                }
            }
            mListDatas.clear();
            mListDatas.addAll(tempList);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void readIDcard(View view) {
        //跳转到德生的idcard身份证刷卡
//		Intent intent = new Intent(this, IDCardActivity_desheng.class);
        Intent intent = new Intent(this, IDCardActivity.class);
        startActivityForResult(intent, 0);
    }

    //蓝牙身份证读卡器
    public void readIDcard_SB(View view) {
        //跳转到德生的idcard社保卡刷卡
//		Intent intent = new Intent(this, IDCardActivity_SB.class);
//		Intent intent = new Intent(this, IDCardActivity_SB_waizhi.class);
        Intent intent = new Intent(this, com.szosen.jkzj.IDCardActivity.class);
        startActivityForResult(intent, 0);
    }

    /***
     * 选择了用户点击删除。
     * @param view
     */
    public void deleteUser(View view) {
        AlertDialog dialog = showDeleteDialog();
        dialog.show();
    }

    private AlertDialog showDeleteDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                UserListActivity.this);
        LayoutInflater inflater = (LayoutInflater) UserListActivity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tl = (LinearLayout) inflater.inflate(
                R.layout.activity_tiwen_dialog_chancedevice, null);
        final ListView lv_btdevice_lists = (ListView) tl
                .findViewById(R.id.lv_btdevice_lists);
        final LinearLayout ll_password = (LinearLayout) tl
                .findViewById(R.id.ll_tiwen_password);
        final EditText et_password = (EditText) ll_password
                .findViewById(R.id.et_tiwen_password);
        final TextView et_inputMessage = (TextView) ll_password
                .findViewById(R.id.tv_tiwen_password_pleaseInputPWD);
        et_inputMessage.setText("需要删除数据，请输入123456：");
        ll_password.setVisibility(View.VISIBLE);
        lv_btdevice_lists.setVisibility(View.GONE);
        builder.setView(tl);
        builder.setTitle("警告");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (ll_password.getVisibility() != View.VISIBLE) {
                    return;
                }
                String password = et_password.getText().toString();
                if (!TextUtils.isEmpty(password)
                        && password.equals("123456")) {
                    //开始删除数据
                    LinkedHashMap<String, String> map = mAdapter.getMapData();
                    JSONDBService dbService = JSONDBService.getInstance(context);
                    ArchiveBean hr = new ArchiveBean();
                    Iterator iter = map.entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry entry = (Map.Entry) iter.next();
                        String time = (String) entry.getValue();
                        hr.setTime(time);
                        JSONDBService.delete(hr);
                    }
                    ToastTool.showShort(context, "数据删除完成");
                    //重新加载数据
                    loadData();
                    mAdapter.putAllDataSelected(false);
                } else {
                    ToastTool.showShort(context, "密码不正确！");
                }
            }

        });
        builder.setNegativeButton("取消", null);
        return builder.create();
    }


    String message_print1 = "最多打印";
    String message_print2 = "份数据，请重新选择用户！";
    /***
     * what handler发送一个打印完成的消息
     */
    public static final int WHAT_PRINTOK = 0x22;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_PRINTOK:
                    if (mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    break;
                case FourCloumAdpter.what_refresh_data:
                    int size = mAdapter.getMapData().size();
                    tv_selectedShow.setText(size + "人");
                    break;
            }
        }
    };
    AlertDialog mDialog;

    /***
     * 选择了用户点击批量打印
     * @param view
     */
    public void printSelected(View view) {
        //显示对话框
        LinkedHashMap<String, String> map = mAdapter.getMapData();
        Log.i(getLocalClassName(), "map集合是：" + map);
        Iterator iter = map.entrySet().iterator();
        ArrayList<String> queryDatas = new ArrayList<>();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String value = (String) entry.getValue();
            queryDatas.add(value);
        }
        String selectItem = (String) sp_role.getSelectedItem();
        //最大的打印的纸张数量
        int maxPrintCountPage = 40;
        //健康档案
        if (ContantsTools.MultiPrint.PRINTITEM_JKDA.equals(selectItem)) {
            if (map.size() > maxPrintCountPage / 2) {
                ToastTool.showLong(context, selectItem + message_print1 + maxPrintCountPage / 2 + message_print2);
                return;
            }
            MultiPrintTool.multiCreateJkda(context, queryDatas, mHandler, true);
        } else if (ContantsTools.MultiPrint.PRINTITEM_JKTJ.equals(selectItem)) {
            if (map.size() > maxPrintCountPage / 4) {
                ToastTool.showLong(context, selectItem + message_print1 + maxPrintCountPage / 4 + message_print2);
                return;
            }
            MultiPrintTool.multiCreateJktj(context, queryDatas, mHandler, true);
        } else if (ContantsTools.MultiPrint.PRINTITEM_ECG.equals(selectItem)) {
            if (map.size() > maxPrintCountPage) {
                ToastTool.showLong(context, selectItem + message_print1 + (maxPrintCountPage) + message_print2);
                return;
            }
            MultiPrintTool.multiCreateECG(context, queryDatas, mHandler, true);
        } else if (ContantsTools.MultiPrint.PRINTITEM_CLJL.equals(selectItem)) {
            if (map.size() > maxPrintCountPage) {
                ToastTool.showLong(context, selectItem + message_print1 + maxPrintCountPage + message_print2);
                return;
            }
            MultiPrintTool.multiCreateCLJL(context, queryDatas, mHandler, true);
        } else if (ContantsTools.MultiPrint.PRINTITEM_ECG_RESULT.equals(selectItem)) {
            if (map.size() > maxPrintCountPage) {
                ToastTool.showLong(context, selectItem + message_print1 + maxPrintCountPage + message_print2);
                return;
            }
            MultiPrintTool.multiCreateECG_Result(context, queryDatas, mHandler, true);
        } else if (ContantsTools.MultiPrint.PRINTITEM_SHZL.equals(selectItem)) {
            if (map.size() > maxPrintCountPage) {
                ToastTool.showLong(context, selectItem + message_print1 + maxPrintCountPage + message_print2);
                return;
            }
            MultiPrintTool.multiCreateSHZL(context, queryDatas, mHandler, true);
        } else if (ContantsTools.MultiPrint.PRINTITEM_ZYTZBS.equals(selectItem)) {
            if (map.size() > maxPrintCountPage / 2) {
                ToastTool.showLong(context, selectItem + message_print1 + (maxPrintCountPage / 2) + message_print2);
                return;
            }
            MultiPrintTool.multiCreateZYTZBS(context, queryDatas, mHandler, true);
        }
        mDialog = showDialog("提示：", "正在生成打印报告，请耐心稍等！", true);
        mDialog.show();
    }

    public void addUser(View view) {
        // 添加用户档案，跳转到新建档案的界面
        Intent intent = new Intent();
        intent.setClass(this, JKDAActivity.class);
        intent.putExtra("flag", "addUser");
        startActivity(intent);
    }

    /***
     * 从本地数据库获取所有的用户数据，以健康档案为准
     *
     */
    public void loadData() {
        // 因为是全部更新，所以更新前先清空集合
        mListDatas.clear();
        dbService = JSONDBService.getInstance(context);
        List<Object> list = dbService.getAll(new ArchiveBean());
        hrs = new ArrayList<ArchiveBean>();
        for (int i = list.size() - 1; i >= 0; i--) {
            ArchiveBean ab = (ArchiveBean) list.get(i);
            // String[] 的gettime为主键。
            hrs.add(ab);
            mListDatas.add(new String[]{ab.getName(), Tools.getYearoldByIdcard(ab.getIdcard()) + "", ab.getIdcard(),
                    ab.getSex(), ab.getTime(), (i + 1) + ""});
            mAdapter.notifyDataSetChanged();
        }
        mAdapter.notifyDataSetChanged();
    }

}
